package lv.dysnomia.songs.server.wiki

import scala.collection.mutable.Queue

class Buffer {
  val result: Queue[WikiBlock] = Queue[WikiBlock]()
  var lastPars = Queue[Queue[String]]()
  var lastPar = Queue[String]()
  var listType = '#'

  def startPBlock(line: String): Unit = {
    lastPar = Queue[String]()
    lastPar.enqueue(line)
  }

  /**
   * append one more line to the current paragraph
   * @param line
   */
  def appendToP(line: String): Unit = {
    lastPar.enqueue(line)
  }

  /**
   * terminate the current paragraph
   */
  def endPBlock(): Unit = {
    val block = PBlock(WikiParser.parseExpr(lastPar.mkString("\n")))
    result.enqueue(block)
  }

  /**
   * start new list
   * @param line
   */
  def startListBlock(line: String): Unit = {
    lastPars = Queue[Queue[String]]()
    lastPar = Queue[String]()
    lastPar.enqueue(line)
  }

  /**
   * append one more line to the current item in the list
   * @param line
   */
  def appendToListItem(line: String): Unit = {
    lastPar.enqueue(line)
  }

  /**
   * make a new item within the current list
   * @param line
   */
  def appendToListBlock(line: String): Unit = {
    lastPars.enqueue(lastPar)
    lastPar = Queue[String]()
    lastPar.enqueue(line)
  }

  def endListBlock(listType: Char): Unit = {
    lastPars.enqueue(lastPar)
    val items = lastPars.toList.map(
      x => WikiParser.parseExpr(x.mkString("\n")))
    val block: WikiBlock = if (listType == '#') OlBlock(items)
    else UlBlock(items)
    result.enqueue(block)
  }

  def getWikiBlocks(): List[WikiBlock] = {
    result.toList
  }

}